package io.renren.modules.frt.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.frt.entity.DistrictEntity;
import io.renren.modules.frt.entity.HistoryEntity;
import io.renren.modules.frt.entity.MonitorExcelEntity;
import io.renren.modules.frt.entity.TaskEntity;
import io.renren.modules.frt.entity.TemplateEntity;
import io.renren.modules.frt.service.DistrictService;
import io.renren.modules.frt.service.HistoryService;
import io.renren.modules.frt.service.MonitorExcelService;
import io.renren.modules.frt.service.MonitorHisService;
import io.renren.modules.frt.service.TaskService;
import io.renren.modules.frt.service.TemplateService;
import io.renren.modules.frt.utils.tpl.ExcelUtils;
import io.renren.modules.frt.utils.tpl.SheetData;
import io.renren.modules.sys.controller.AbstractController;



/**
 * 历史汇总数据
 *
 * @author qibing.huang
 * @email abingtech@163.com
 * @date 2018-12-04 14:02:52
 */
@RestController
@RequestMapping("frt/history")
public class HistoryController extends AbstractController {
    @Autowired
    private HistoryService historyService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TemplateService templateService;
    @Autowired
	private MonitorHisService monitorHisService;
    @Autowired
    private MonitorExcelService monitorExcelService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("frt:history:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = historyService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("frt:history:info")
    public R info(@PathVariable("id") Long id){
        HistoryEntity history = historyService.selectById(id);

        return R.ok().put("history", history);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("frt:history:save")
    public R save(@RequestBody HistoryEntity history){
    	
    	history.setCreateTime(new Date());
    	DistrictEntity province = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", history.getProvince()));
    	history.setProvinceName(province.getName());
    	TaskEntity task = taskService.selectById(history.getTaskId());
    	history.setTaskName(task.getName());
    	history.setTempName(templateService.selectById(history.getTempId()).getName());
    	history.setUserId(this.getUserId());
    	history.setUsername(this.getUser().getUsername());
    	history.setNodeDate(task.getNodeDate());
		historyService.insert(history);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("frt:history:update")
    public R update(@RequestBody HistoryEntity history){
    	
    	DistrictEntity province = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", history.getProvince()));
    	history.setProvinceName(province.getName());
    	TaskEntity task = taskService.selectById(history.getTaskId());
    	history.setTaskName(task.getName());
    	history.setTempName(templateService.selectById(history.getTempId()).getName());
    	history.setNodeDate(task.getNodeDate());
    	
		historyService.updateById(history);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("frt:history:delete")
    public R delete(@RequestBody Long[] ids){
		historyService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
    
    /**
	 * 下载表1汇总数据
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void download(@RequestBody Long[] ids, HttpServletResponse response) {
		List<? extends Object> list = null;
		String sheetName = "";
		StringBuffer title = new StringBuffer("");
		
		if(ids == null || ids.length == 0) {
			logger.error("参数不合法！");
			return;
		}
		List<HistoryEntity> hisList = historyService.selectBatchIds(Arrays.asList(ids));
		String tempType = "forestry_monitor";
		for(HistoryEntity his : hisList) {
			TemplateEntity temp = templateService.selectById(his.getTempId());
			if(!tempType.equals(temp.getType())) {
				logger.error("参数不合法！");
				return;
			}
		}
		
		List<String> codeList = new ArrayList<>();
		List<MonitorExcelEntity> excelList = monitorExcelService
				.selectList(new EntityWrapper<MonitorExcelEntity>().isNotNull("index_code"));
		if (excelList == null || excelList.size() == 0) {
			logger.error("未上传excel模板！");
			return;
		}
		for (MonitorExcelEntity excel : excelList) {
			codeList.add(excel.getIndexCode());
		}

		list = monitorHisService.sumaryList(ids, codeList);
		sheetName = ExcelUtils.TPL_MONITOR_REPORT1;
		SheetData sd = new SheetData(sheetName);
		sd.addDatas(list);
		sd.put("title", title.toString());
		sd.put("date", io.renren.common.utils.DateUtils.format(new Date(), "yyyy年MM月dd日"));

		try {
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition",
					String.format("attachment; filename=\"%s\"", new String((sheetName + ExcelUtils.SUBFIX).getBytes("GBK"), "ISO8859-1")));

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		try {
			ExcelUtils.writeData(sheetName + ExcelUtils.SUBFIX, response.getOutputStream(), sd);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}


}
